package com.signway.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;

import org.xmlpull.v1.XmlSerializer;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;

/**
 * 文件工具类
 */
public class FileTools {
    private static final String TAG = "FileTools";

    private static String sysDir = null;

    public static String getSysDir() {
        if (sysDir == null) {
            sysDir = Environment.getExternalStorageDirectory().toString();
        }
        return sysDir;
    }

    /**
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            if (myFilePath.exists()) {
                myFilePath.delete(); // 删除空文件夹
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        if (tempList == null) {
            return flag;
        }

        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static long getlastModifiedTime(String dir, String fileName) {
        if (dir == null || fileName == null) {
            return 0;
        }
        File file = new File(dir, fileName);
        if (file != null && file.exists()) {
            long lastModified = file.lastModified();
            Log.i(TAG, fileName + "'s lastmodify is" + (lastModified + 2000));
            return lastModified + 2000;
        } else {
            return 2;
        }
    }

    /**
     * 获取文件的大小
     */
    @SuppressWarnings("resource")
    public static long getFileSizes(String dir, String fileName) {
        long size = 0;
        if (dir == null || fileName == null) {
            return size;
        }

        File file = new File(dir, fileName);
        if (file.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                size = fis.available();
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {

                    }
                }
            }
        } else {
            System.out.println("文件不存在");
            return -1;
        }

        return size;
    }

    /**
     * 获得除去签名的sch文件 文件名字是：file.signway
     */
    public static ByteArrayInputStream getNewSCHStream(String file) {
        File schfile = new File(file);
        if (!schfile.exists()) {
            return null;
        }
        if (schfile.isDirectory()) {
            return null;
        }
        FileInputStream fis = null;
        byte[] bytes = null;
        try {
            fis = new FileInputStream(schfile);
            long filesize = schfile.length();
            if (filesize == 0) {
                return null;
            }
            bytes = new byte[(int) filesize - 40];
            fis.read(bytes, 0, (int) (filesize - 40));
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得除去签名的lastmodify文件 文件名字是：file.signway
     */
    public static String getNewXMLFile(String file) {
        File schfile = new File(file);
        if (!schfile.exists()) {
            return null;
        }
        if (schfile.isDirectory()) {
            return null;
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(schfile);
            InputStreamReader input = new InputStreamReader(fis);
            BufferedReader reader = new BufferedReader(input);
            int size = (int) ((schfile.length() / 1024) + 1) * 1024;
            long filesize = schfile.length();
            if (filesize == 0) {
                return null;
            }
            char[] cbuf = new char[size];
            reader.read(cbuf);
            reader.close();
            String tempfile = file.substring(0, file.indexOf(".")) + ".signway";
            FileWriter bw = new FileWriter(tempfile);
            bw.write(cbuf, 0, (int) (filesize - 39));
            bw.close();
            return tempfile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // TODO:: need to endswith
    public static int getFileType(String fileNmae) {
        String[] picTypeList = new String[]{".jpg", ".jpeg", ".png", ".bmp",
                ".gif"};
        String[] videoTypeList = new String[]{".flv", ".avi", ".mpeg",
                ".wmv", ".mpg", ".ra", ".rm", ".ram", ".rmvb", ".dat", ".mov",
                ".asf", ".mtv", ".mkv", ".3gp", ".mp4", ".amv", ".dmv",
                ".divx", ".swf", ".ts"};

        for (int i = 0; i < picTypeList.length; i++) {
            if (fileNmae.toLowerCase().contains(picTypeList[i])) {
                return 0;
            }
            if (fileNmae.toLowerCase().contains(videoTypeList[i])) {
                return 1;
            }
        }

        for (int i = picTypeList.length; i < videoTypeList.length; i++) {
            if (fileNmae.toLowerCase().contains(videoTypeList[i])) {
                return 1;
            }
        }
        return 2;
    }

    public static final int DIR_TYPE_PIC = 0;
    public static final int DIR_TYPE_VIDEO = 1;
    public static final int DIR_TYPE_AUDIO = 2;
    public static final int DIR_TYPE_INTER = 3;
    public static final int DIR_TYPE_UNKNOW = 4;
    public static final int DIR_TYPE_IMP = 6;
    public static final int DIR_TYPE_FM_MEDIA = 7;

    /*
     * 文件类型 ret: 0：pic 1：video 2：music 3：interactive  4:unknown
     */
    public static int getDirType(String fileName) {
        String[] picTypeList = new String[]{".jpg", ".jpeg", ".png", ".bmp",
                ".gif", ".jfif"};
        String[] videoTypeList = new String[]{".flv", ".avi", ".mpeg",
                ".wmv", ".mpg", ".ra", ".rm", ".ram", ".rmvb", ".dat", ".mov",
                ".asf", ".mtv", ".mkv", ".3gp", ".mp4", ".amv", ".dmv",
                ".divx", ".swf", ".ts", ".vob"};
        String[] audioTypeList = new String[]{".mp3", ".aac", ".wma", ".wav", ".amr"};
        String[] interTypeList = new String[]{".zip"};
        String[] impTypeList = new String[]{".imp", ".iss"};

        if (fileName == null) {
            return DIR_TYPE_UNKNOW;
        }

        for (int i = 0; i < interTypeList.length; i++) {
            if (fileName.toLowerCase().endsWith(interTypeList[i])) {
                return DIR_TYPE_INTER;
            }
        }

        for (int i = 0; i < audioTypeList.length; i++) {
            if (fileName.toLowerCase().endsWith(audioTypeList[i])) {
                return DIR_TYPE_AUDIO;
            }
        }

        for (int i = 0; i < picTypeList.length; i++) {
            if (fileName.toLowerCase().endsWith(picTypeList[i])) {
                return DIR_TYPE_PIC;
            }
            if (fileName.toLowerCase().endsWith(videoTypeList[i])) {
                return DIR_TYPE_VIDEO;
            }
        }

        for (int i = 0; i < impTypeList.length; i++) {
            if (fileName.toLowerCase().endsWith(impTypeList[i])) {
                return DIR_TYPE_IMP;
            }
        }

        for (int i = picTypeList.length; i < videoTypeList.length; i++) {
            if (fileName.toLowerCase().endsWith(videoTypeList[i])) {
                return DIR_TYPE_VIDEO;
            }
        }
        return DIR_TYPE_UNKNOW;
    }

    public static int getDirType(String filename, boolean isContainZip) {
        if (isContainZip) {
            return getDirType(filename);
        } else {
            int type = getDirType(filename);
            if (type == DIR_TYPE_INTER) {
                return DIR_TYPE_UNKNOW;
            } else {
                return type;
            }
        }
    }

    /**
     * 获取文件名后缀，如：.jpg
     **/
    public static String getFilePostfix(String fileName) {
        if (fileName == null) {
            return null;
        }

        int index = fileName.lastIndexOf('.');
        if (index == -1) {
            return null;
        }
        return fileName.substring(index);
    }

    /**
     * 获取文件
     *
     * @param path 文件路径
     * @param name 文件名称
     * @return
     */
    public static File getFile(String path, String name) {
        File dir, file = null;
        if (path == null || name == null) {
            Log.i(TAG, "getFile path is " + path);
            Log.i(TAG, "getFile name is " + name);
            return file;
        }
        dir = new File(path);
        if (dir.exists() || dir.mkdirs()) {
            file = new File(dir, name);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    public static File getDir(String path) {
        if (path == null) {
            return null;
        }
        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory()) {
            return null;
        }
        return dir;
    }

    /**
     * 获取文件输出�?
     *
     * @param file 文件
     * @return
     */
    public static FileOutputStream getFileOutputStream(File file) {
        FileOutputStream stream = null;
        if (file == null) {
            Log.i(TAG, "getFileOutputStream stream is " + stream);
            return stream;
        } else {
            try {
                stream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return stream;
    }

    /**
     * 获取输入�?
     *
     * @param file
     * @return
     */
    public static FileInputStream getFileInputStream(File file) {
        FileInputStream stream = null;
        if (file == null) {
            Log.i(TAG, "getFileInputStream stream is " + stream);
            return stream;
        } else {
            try {
                stream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                Log.w(TAG, "get file inputstream error");
            }
        }
        return stream;
    }

    /**
     * 删除文件
     *
     * @param path 文件的绝对路径
     */
    public static void deleteFile(String path) {
        if (path == null) {
            Log.i(TAG, "deleteFile path is" + path);
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 删除根目录下文件
     *
     * @param path
     */
    public static void deleteDir(String path) {
        if (path == null) {
            Log.i(TAG, "deleteDir path is" + path);
            return;
        }
        File dir = new File(path);
        if (dir.isDirectory()) {
            for (File file : dir.listFiles()) {
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 递归删除目录下所有文件，目录
     *
     * @param dir
     */
    public static void deleteDirALl(File dir) {
        if (dir == null) {
            Log.e(TAG, "deleteDirALl: dir == null");
            return;
        }
        Log.i(TAG, "deleteDirALl: dir = " + dir);

        if (dir.isFile()) {
            dir.delete();
            Log.e(TAG, "dir.isFile()");
            return;
        }

        if (dir.isDirectory()) {
            File[] childFiles = dir.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                Log.e(TAG, "childFiles == null");
                dir.delete();
                return;
            }
            Log.i(TAG, "childFiles.length == " + childFiles.length);
            for (int i = 0; i < childFiles.length; i++) {
                deleteDirALl(childFiles[i]);
            }
            dir.delete();
        }
    }

    /**
     * 写map数据
     *
     * @param outputStream
     * @param map
     */
    public static void write(FileOutputStream outputStream,
                             Map<String, String> map) {
        if (outputStream == null || map == null) {
            Log.i(TAG, "write outputStream is " + outputStream);
            Log.i(TAG, "write map is " + map);
            return;
        }
        try {
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(outputStream, "UTF-8");
            serializer.startDocument("UTF-8", null);
            String tag2 = null;
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                String value = map.get(key);
                if (value == null) {
                    serializer.startTag(null, key);
                    tag2 = key;
                } else {
                    serializer.attribute(null, key, value);
                }
            }
            serializer.endTag(null, tag2);
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                String value = map.get(key);
                // TODO 倒序
                if (value == null && key != tag2) {
                    serializer.endTag(null, key);
                }
            }
            serializer.endDocument();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 写byte[]数据
     *
     * @param outputStream
     * @param data
     */
    public static void write(FileOutputStream outputStream, byte[] data) {
        if (outputStream == null || data == null) {
            Log.i(TAG, "write outputStream is " + outputStream);
            Log.i(TAG, "write data is " + data);
            return;
        }
        try {
            // byte[] dst = new byte[1024];
            // System.arraycopy(src, srcPos, dst, dstPos, length)
            // TODO:将write()改成write(data, 0, length)
            outputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取目录文件的大小, 字节
     */
    public static long getDirSize(File dir) {
        long fileSize = -1;
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return fileSize;
        }

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file == null || !file.exists()) {
                continue;
            }

            if (file.isDirectory()) {
                fileSize += getDirSize(file);
            } else if (file.isFile()) {
                long size = getFileSize(file);
                if (size > 0) {
                    fileSize += size;
                }
            }
        }

        return fileSize;
    }

    /**
     * 获取文件的大小, 单位字节
     */
    public static long getFileSize(File file) {
        long fileSize = -1;
        if (file == null || !file.exists()) {
            Log.i(TAG, "getFileSize file is " + file + " or not exists");
            return fileSize;
        }

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            fileSize = inputStream.available();
        } catch (Exception e) {
            Log.w(TAG, "file error: " + e.toString());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    Log.w(TAG, "close inputStream error: " + e.toString());
                }
            }
        }
        return fileSize;
    }

    public static String getFilePath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }

        int position = filePath.lastIndexOf('/');
        if (position < 0) {
            return filePath;
        }

        return filePath.substring(0, position);
    }

    /**
     * 获取没有后缀名的文件名称
     */
    public static String getFileName(File file) {
        String name = null;
        if (file == null || !file.exists()) {
            Log.i(TAG, "getFileName file is " + file + " or not exists");
            return name;
        }
        // 文件名称(含有后缀)
        String fileName = file.getName();
        if (fileName == null) {
            return name;
        }
        int last = fileName.lastIndexOf('.');
        if (last == -1) {
            return name;
        }
        return fileName.substring(0, last);
    }

    public static String getFileName(String file) {
        if (file == null) {
            return null;
        }
        int start = file.lastIndexOf('/');
        if (start < 0) {
            start = 0;
        }
        int end = file.lastIndexOf('.');
        if (end < 0) {
            end = file.length();
        }
        return file.substring(start, end);
    }

    public static String[] getFileList(String dir, final String filter) {
        File dirName = new File(dir);
        if (!dirName.exists()) {
            Log.d(TAG, "file not exists");
            return null;
        }
        if (!dirName.isDirectory()) {
            Log.d(TAG, "file is not a directory");
            return null;
        }

        return dirName.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.toLowerCase().endsWith(filter);
            }
        });
    }

    /**
     * 创建目录
     *
     * @param destDirName 目标目录名
     * @return 目录创建成功返回true，否则返回false
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return true;
        }
        // 创建单个目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    private static boolean isExistPath(String path) {
        File file = new File(path);
        if (file.exists() && file.canRead()) {
            return true;
        }

        return false;
    }

    public static synchronized StatFs getStatFs(String path) {
        StatFs stat = null;

        if (!isExistPath(path)) {
            return null;
        }

        try {
            stat = new StatFs(path);
        } catch (Exception e) {
            stat = null;
        }

        return stat;
    }

    /**** sdcard 空闲的容量，单位为G ****/
    public static synchronized float getAvailaleSizeUnitG(String path) {
        StatFs stat = getStatFs(path);
        if (stat == null) {
            Log.w(TAG, "getAvailaleSize: stat null");
            return 0;
        }

        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        float all = availableBlocks * blockSize;

        return all / 1024 / 1024 / 1024;
    }

    /**** sdcard 总容量  单位为G ****/
    public static synchronized float getAllSizeUnitG(String path) {
        StatFs stat = getStatFs(path);
        if (stat == null) {
            Log.w(TAG, "getAllSize: stat null");
            return 0;
        }

        long blockSize = stat.getBlockSizeLong();
        long blocks = stat.getBlockCountLong();
        float all = blocks * blockSize;

        return all / 1024 / 1024 / 1024;
    }

    /**
     * 获得磁盘总空间，单位B
     */
    public static synchronized long getAllSize(String path) {
        StatFs stat = getStatFs(path);
        if (stat == null) {
            Log.w(TAG, "getAllSize: stat null");
            return 0;
        }

        long blockSize = stat.getBlockSizeLong();
        long blockCount = stat.getBlockCountLong();
        long sd = blockCount * blockSize;

        return sd;
    }

    /**
     * 获得磁盘可利用的空间，单位B
     */
    public static synchronized long getAvailableSize(String path) {
        StatFs stat = getStatFs(path);
        if (stat == null) {
            Log.w(TAG, "getAvailableSize: stat null");
            return 0;
        }

        long blockSize = stat.getBlockSizeLong();
        long blocksAvailable = stat.getAvailableBlocksLong();
        long sdAvail = blocksAvailable * blockSize;

        return sdAvail;
    }

    /**
     * 获得磁盘已使用空间，单位B
     */
    public static long getUsedSize(String path) {
        return getAllSize(path) - getAvailableSize(path);
    }

    /**
     * 检查监播离线文件是否存在
     *
     * @param path
     * @param filename
     * @return
     */
    public static boolean checkPlayLogFileExitByName(String path, String filename) {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            return false;
        }
        if (!dirFile.isDirectory()) {
            return false;
        }
        String[] fileList = dirFile.list();
        if (fileList == null) {
            return false;
        }
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i] != null) {
                if ((fileList[i].contains(filename)) && (!(fileList[i].contains("zip")))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 将文件夹中的文件的指定后缀名去掉
     *
     * @param dirPath
     * @param suffix
     */
    public static void removeFileSuffixByDir(String dirPath, String suffix) {
        File dirFile = new File(dirPath);
        Log.v(TAG, "removeFileSuffixByDir: dirPath = " + dirPath + " suffix = " + suffix);
        if (dirFile.exists() && dirFile.isDirectory()) {
            String[] fileList = dirFile.list();
            if ((fileList != null) && (fileList.length > 0)) {
                for (int i = 0; i < fileList.length; i++) {
                    if (fileList[i] == null) {
                        continue;
                    }
                    Log.v(TAG, "removeFileSuffixByDir: check file " + dirPath + fileList[i]);
                    File file = new File(dirPath + fileList[i]);
                    if (file.exists()) {
                        if (file.isDirectory()) {
                            removeFileSuffixByDir(file.getPath() + "/", suffix);
                        } else {
                            if (fileList[i].endsWith("." + suffix)) {
                                int dot = fileList[i].lastIndexOf(".");
                                String dstFilename = fileList[i].substring(0, dot);
                                File dstFile = new File(dirPath + dstFilename);
                                if (dstFile.exists()) {
                                    dstFile.delete();
                                }
                                boolean ret = file.renameTo(dstFile);
                                Log.i(TAG, "removeFileSuffixByDir: " + file.getPath() + " - " + dstFile.getPath() + " ret = " + ret);
                            }
                        }
                    }
                }
            }
        }
    }

    public static boolean createNewFile(String filePath, boolean needDelete) {
        File file = new File(filePath);
        if (needDelete) {
            if (file.exists()) {
                file.delete();
            }
        } else {
            if (file.exists()) {
                return true;
            }
        }

        try {
            file.createNewFile();
        } catch (IOException e) {
            return false;
        }

        return true;
    }

    public static boolean copyAssetFileToLocal(Context context, String assetFilePath, String localPath) {
        String[] assetFileNameList = null;
        if (context == null) {
            return false;
        }
        AssetManager assetManager = context.getAssets();
        try {
            assetFileNameList = assetManager.list(assetFilePath);
        } catch (Exception e) {
            assetFileNameList = null;
        }

        if ((assetFileNameList == null) || (assetFileNameList.length <= 0)) {
            return false;
        }

        File localDir = new File(localPath);
        if (!localDir.exists()) {
            localDir.mkdirs();
        }

        byte[] buffer = new byte[32 * 1024];

        boolean hasCopyFile = false;

        for (String assetFileName : assetFileNameList) {
            String filePath = assetFilePath + "/" + assetFileName;

            try {
                String list[] = assetManager.list(filePath);
                if ((list != null) && (list.length > 0)) { // dir
                    continue;
                }
            } catch (Exception e) {

            }

            File localFile = new File(localDir.getAbsolutePath(), assetFileName);
            if (localFile.exists()) {
                localFile.delete();
            }

            InputStream inputStream = null;
            FileOutputStream fos = null;
            try {
                inputStream = assetManager.open(filePath);

                fos = new FileOutputStream(localFile);

                int length = 0;
                while ((length = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                }
                fos.flush();
                hasCopyFile = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {

                    }
                }

                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {

                    }
                }
            }
        }

        return hasCopyFile;
    }


    /**
     * 获取文件夹大小
     *
     * @param file
     * @return
     */
    public static long getFolderSize(java.io.File file) {
        long size = 0;
        if (file == null) {
            return 0;
        }
        if (!file.exists()) {
            return 0;
        }
        try {
            java.io.File[] fileList = file.listFiles();
            if (fileList == null) {
                return 0;
            }
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
        }
        return size;
    }

    /**
     * 统计文件夹中的文件数量
     *
     * @param file
     * @return
     */
    public static int getFolderFileNunms(File file) {
        int size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size += getFolderFileNunms(fileList[i]);
                } else {
                    size++;
                }
            }
        } catch (Exception e) {
        }
        return size;
    }

    /*
     * 方法名：getDirFilesCount
     * 作用：统计.txt文件个数
     */
    public static int getDirFilesCount(File srcFile) {
        int count = 0;
        if (srcFile == null) {
            return 0;
        }
        if (!srcFile.exists()) {
            return 0;
        }
        if (!srcFile.isDirectory()) {
            return 0;
        }
        // 把所有目录、文件放入数组
        File[] files = srcFile.listFiles();
        // 遍历数组每一个元素
        for (File f : files) {
            // 判断元素是不是文件夹，是文件夹就重复调用此方法（递归）
            if (f.isDirectory()) {
                count += getDirFilesCount(f);
            } else {
                count++;
            }
        }
        return count;
    }

    public static boolean isSameFile(File file1, File file2) {
        if (file1.lastModified() != file2.lastModified()) {
            return false;
        }

//        Log.i(TAG, "file len1 = " + file1.length() + "; len2 = " + file2.length());
        if (file1.length() != file2.length()) {
            return false;
        }

        FileInputStream fis1 = null;
        FileInputStream fis2 = null;

        try {
            byte[] buffer1 = new byte[48];
            byte[] buffer2 = new byte[48];

            fis1 = new FileInputStream(file1);
            if (file1.length() > 40) {
                fis1.skip(file1.length() - 40);
            }
            int readLen1 = fis1.read(buffer1, 0, 40);

            fis2 = new FileInputStream(file2);
            if (file2.length() > 40) {
                fis2.skip(file2.length() - 40);
            }
            int readLen2 = fis2.read(buffer2, 0, 40);

            if (readLen1 != readLen2) {
                Log.e(TAG, "isSameFile read len not equal len1 = " + readLen1 + "; len2 = " + readLen2);
                return false;
            } else {
                for (int i = 0; i < readLen1; i++) {
                    if (buffer1[i] != buffer2[i]) {
//                    Log.i(TAG, "file buffer1[i] = " + buffer1[i] + "; buffer2[i] = " + buffer2[i]);
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        } finally {
            if (fis1 != null) {
                try {
                    fis1.close();
                } catch (IOException e) {

                }
                fis1 = null;
            }

            if (fis2 != null) {
                try {
                    fis2.close();
                } catch (IOException e) {

                }
                fis2 = null;
            }
        }

        return true;
    }

}
